package com.cn.xiaonuo.modular.service.app;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cn.xiaonuo.core.util.StringUtils;
import com.cn.xiaonuo.modular.dao.UserInfoDao;
import com.cn.xiaonuo.modular.model.app.UserInfo;

@Service
public class UserInfoService {
	
	@Autowired
	private UserInfoDao appUserDao;
	
	public UserInfo findUserInfo(Long userId) {
		return appUserDao.single(userId);
	}
	
	public UserInfo insert(String mobile,String appCode) {
		UserInfo user = new UserInfo();
		user.setMobile(mobile);
		user.setAppCode(appCode);
		user.setRealName("匿名用户");
		user.setSex(0);
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		appUserDao.insert(user);
		return getAppUser(mobile, appCode);
	}
	
	/**
	 * 先通过电话号码获取用户信息，未找到则用appCode查找
	 * @param mobile
	 * @param appCode
	 * @return
	 */
	public UserInfo getAppUser(String mobile,String appCode) {
		if(StringUtils.isEmpty(mobile)) {
			return findByAppCode(appCode);
		}
		UserInfo user = findByMobile(mobile);
		if(null == user) {
			return findByAppCode(appCode);
		}
		return user;
	}
	
	/**
	 * 通过手机号码查找
	 * @param moblie
	 * @return
	 */
	public UserInfo findByMobile(String moblie) {
		return appUserDao.createLambdaQuery()
				.andEq(UserInfo :: getMobile, moblie).single();
	}
	
	public UserInfo findByAppCode(String appCode) {
		return appUserDao.createLambdaQuery()
				.andEq(UserInfo :: getAppCode, appCode).single();
	}
	
	/**
	 * 编辑用户资料
	 * @param user
	 */
	public void updateAppUser(UserInfo user) {
		UserInfo single = appUserDao.single(user.getId());
		if(null == single) {
			throw new RuntimeException("当前用户信息不存在，请刷新再试！");
		}
		appUserDao.updateTemplateById(user);
	}

}
